package ari.com.eft.startup;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

import ari.com.eft.jobs.NettyJob;
import ari.com.netty.server.NettyEchoServer;

import com.ari.eft.transport.tls.EPPTLSTransport;

public class ServletContextAppListener implements ServletContextListener {
	Scheduler scheduler = null;
	Logger logger = Logger.getLogger(ServletContextAppListener.class
			.getSimpleName());
	EPPTLSTransport tlsTransport = null;

	@Override
	public void contextInitialized(final ServletContextEvent pServletContext) {
		System.out.println("Starting EFT now");
		try {
			scheduler = StdSchedulerFactory.getDefaultScheduler();
			scheduler.addJob(new JobDetail("NETTY_JOB", "NETTY_GROUP",
					NettyJob.class), true);
			scheduler.triggerJob("NETTY_JOB", "NETTY_GROUP");
			scheduler.start();
			logger.debug("Logging at DEBUG" + " cheers - started :)");
		} catch (final SchedulerException pScehdulerException) {
			pScehdulerException.printStackTrace();
		}

		// /* Create the connection to EPPD */
		// SessionManagerProperties sessionMgrProps = null;
		// try {
		// sessionMgrProps = new SessionManagerPropertiesImpl(
		// "toolkit.properties");
		// } catch (final FileNotFoundException e1) {
		// // TODO Auto-generated catch block
		// e1.printStackTrace();
		// } catch (final IOException e1) {
		// // TODO Auto-generated catch block
		// e1.printStackTrace();
		// }
		// sessionMgrProps.getSessionProperties();
		//
		// try {
		// tlsTransport = EFTTransportMgr.getEPPTransportInstance();
		// } catch (final SessionConfigurationException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }

	}

	@Override
	public void contextDestroyed(final ServletContextEvent sce) {
		try {
			NettyEchoServer.stop();
			scheduler.shutdown();
			// tlsTransport.close();
		} catch (final SchedulerException pScehdulerException) {
			pScehdulerException.printStackTrace();
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}
}
